<?php

namespace App\Http\Controllers\Home;

use App\Model\Article;
use App\Model\Cate;
use App\Model\Collect;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class IndexController extends CommonController
{
    //前台首页
    public function index(){
        $cate_arts = Cate::where('cate_pid','<>',0)->with('article')->get();
        //dd($cate_arts);
        return view("home.index",compact('cate_arts'));
    }
    //文章收藏
    public function collect(Request $request){
        //获取ajax提交的数据
        $uid = $request->input('uid');
        $artid = $request->input('artid');
        $act = $request->input('act');

        //判断是收藏还是取消收藏操作
       switch ($act){
           //收藏操作
           case 'add':
               //判断是否被收藏
                $collect = Collect::where([
                    ['uid',$uid],
                    ['art_id',$artid]
                ])->get();
                //未被收藏
                if($collect->isEmpty()){
                    //添加收藏记录
                    $res = Collect::create([
                        'uid'=>$uid,
                        'art_id'=>$artid
                    ]);
                    //文章收藏加一
                    Article::where('art_id',$artid)->increment('art_collect');
                    //如果收藏成功
                    if($res){
                        return response()->json(['status'=>0,'msg'=>'已收藏']);
                    }else{
                        return response()->json(['status'=>1,'msg'=>'收藏失败']);
                    }
                }else{
                    return response()->json(['status'=>0,'msg'=>'已收藏']);
                }
               break;
           //取消收藏操作
           case 'remove':
               //判断是否被收藏
               $collect = Collect::where([
                   ['uid',$uid],
                   ['art_id',$artid]
               ])->first();
               //已收藏
               if(!empty($collect)){
                   //文章收藏减一
                   Article::where('art_id',$artid)->decrement('art_collect');
                   //取消收藏
                   $res = $collect->delete();
                   if($res){
                       return response()->json(['status'=>0,'msg'=>'请收藏']);
                   }else{
                       return response()->json(['status'=>1,'msg'=>'取消收藏失败']);
                   }
               }else{
                   return response()->json(['status'=>0,'msg'=>'请收藏']);
               }
               break;
       }

    }

    //文章详情
    public function detail(){
        return view("home.detail");
    }

    //列表页
    public function lists(){
        return view("home.lists");
    }
}
